package bma.common.langutil.concurrent;

import java.util.concurrent.TimeUnit;

public class ScheduledExecutorTM implements ScheduledExecutor {

	final org.slf4j.Logger log = org.slf4j.LoggerFactory
			.getLogger(ScheduledExecutorTM.class);

	private TimerManager timer;

	public ScheduledExecutorTM() {
		super();
	}

	public ScheduledExecutorTM(TimerManager timer) {
		super();
		this.timer = timer;
	}

	public TimerManager getTimer() {
		return timer;
	}

	public void setTimer(TimerManager timer) {
		this.timer = timer;
	}

	@Override
	public boolean schedule(Runnable command, long delay, TimeUnit unit) {
		return _delay(command, delay, unit);
	}

	protected boolean _delay(Runnable command, long delay, TimeUnit unit) {
		ProcessTimerTask task = TimerManager.delay(command,
				unit.toMillis(delay));
		return timer.postTimerTask(task);
	}

	@Override
	public boolean scheduleAtFixedRate(final Runnable command,
			long initialDelay, final long period, final TimeUnit unit) {
		Runnable r = new Runnable() {

			@Override
			public void run() {
				long tm = System.currentTimeMillis();
				try {
					command.run();
					long delay = System.currentTimeMillis() - tm
							- unit.toMillis(period);
					if (delay < 0)
						delay = 0;
					_delay(this, delay, TimeUnit.MILLISECONDS);
				} catch (Exception e) {
					if (log.isDebugEnabled()) {
						log.debug("stop: {} run fail - {}", command,
								e.getMessage());
					}
				}
			}
		};
		ProcessTimerTask task = TimerManager.schedule(r,
				unit.toMillis(initialDelay));
		return timer.postTimerTask(task);
	}

	@Override
	public boolean scheduleWithFixedDelay(final Runnable command,
			long initialDelay, final long delay, final TimeUnit unit) {
		Runnable r = new Runnable() {

			@Override
			public void run() {
				try {
					command.run();
					_delay(this, delay, unit);
				} catch (Exception e) {
					if (log.isDebugEnabled()) {
						log.debug("stop: {} run fail - {}", command,
								e.getMessage());
					}
				}
			}
		};
		return _delay(r, initialDelay, unit);
	}

}
